package com.tushen.datacenter.ts;


import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.common.util.AesEncryptUtils;
import com.common.util.DateUtil;
import com.common.util.ImageUtil;
import com.common.view.ViewAdjust;
import com.common.viewinject.ViewInject;
import com.common.viewinject.ViewUtils;
import com.tushen.datacenter.ts.adpter.BanzuAdapter;
import com.tushen.datacenter.ts.adpter.StatusAdapter;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import org.apache.commons.codec.binary.StringUtils;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.*;


/*
 * Main Activity class that loads {@link MainFragment}.
 */
public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private List<JinChuStatusBean> JinChuData = new ArrayList<>();
    private List<BanzuBean> BanzuData1 = new ArrayList<>();
    private List<BanzuBean> BanzuData2 = new ArrayList<>();
    private List<BanzuBean> BanzuData3 = new ArrayList<>();

    private UdpReceiveThread udpReceiveThread;

    MessageHandler handler = new MessageHandler(this);

    private Activity mContext;

    private View rootView;

    @ViewInject(value = R.id.iv_renyuan_image)
    private ImageView renyuan_image;
    @ViewInject(value = R.id.tv_renyuan_name)
    private TextView tv_renyuan_name;
    @ViewInject(value = R.id.tv_renyuan_company)
    private TextView tv_renyuan_company;
    @ViewInject(value = R.id.tv_banzu_name)
    private TextView tv_banzu_name;
    @ViewInject(value = R.id.tv_gongzhong_name)
    private TextView tv_gongzhong_name;
    @ViewInject(value = R.id.tv_fangxiang)
    private TextView tv_fangxiang;
    @ViewInject(value = R.id.tv_shebei)
    private TextView tv_shebei;
    @ViewInject(value = R.id.tv_shijian)
    private TextView tv_shijian;

    @ViewInject(value = R.id.tv_xiangmu_renshu)
    private TextView tv_xiangmu_renshu;
    @ViewInject(value = R.id.tv_xiangmu_chuqing)
    private TextView tv_xiangmu_chuqing;
    @ViewInject(value = R.id.tv_xiangmu_xianchang)
    private TextView tv_xiangmu_xianchang;
    @ViewInject(value = R.id.tv_xiangmu_lv)
    private TextView tv_xiangmu_lv;

    @ViewInject(value = R.id.tv_laowu_renshu)
    private TextView tv_laowu_renshu;
    @ViewInject(value = R.id.tv_laowu_chuqing)
    private TextView tv_laowu_chuqing;
    @ViewInject(value = R.id.tv_laowu_xianchang)
    private TextView tv_laowu_xianchang;
    @ViewInject(value = R.id.tv_laowu_lv)
    private TextView tv_laowu_lv;

    @ViewInject(value = R.id.tv_guanli_renshu)
    private TextView tv_guanli_renshu;
    @ViewInject(value = R.id.tv_guanli_chuqing)
    private TextView tv_guanli_chuqing;
    @ViewInject(value = R.id.tv_guanli_xianchang)
    private TextView tv_guanli_xianchang;
    @ViewInject(value = R.id.tv_guanli_lv)
    private TextView tv_guanli_lv;
    @ViewInject(value = R.id.line_chart)
    private LineChart lineChart;

    @ViewInject(value = R.id.lv_gongzhong)
    private ListView lv_gongzhong;
    @ViewInject(value = R.id.lv_banzu_kaoqin)
    private ListView lv_banzu_kaoqin;
    @ViewInject(value = R.id.lv_danwei_kaoqin)
    private ListView lv_danwei_kaoqin;
    @ViewInject(value = R.id.title)
    private TextView title;
    @ViewInject(value = R.id.tv_ip)
    private TextView tv_ip;

    String[] axisValue = new String[24];
    List<Entry> entries = new ArrayList<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        mContext = this;
        rootView = findViewById(R.id.root_layout);
        ViewAdjust.adjustLayoutParams(this, rootView);
        ViewUtils.inject(this, rootView);

        findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //初始化现场实时人数趋势
        initChart();
    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart ..");
        super.onStart();
        listenStatus = true;
        udpReceiveThread = new UdpReceiveThread();
        udpReceiveThread.start();
    }

    private void intJingChuStatus() {
        //初始化数据
        initJinChuData();
        // 将适配器上的数据传递给listView
        ListView lv_status = findViewById(R.id.lv_jinchu_status);
        StatusAdapter adapter = new StatusAdapter(MainActivity.this, R.layout.jinchu_status_item, JinChuData);
        lv_status.setAdapter(adapter);
    }

    private void initJinChuData() {
        JinChuData.clear();
        int size = inoutList.size();
        for (int i = size -1; i >= 0; i--) {
            //Log.d(TAG, "initJinChuData: " + inoutList.get(i));
            JinChuData.add(inoutList.get(i));
        }
    }

    private void initChart(){
        for (int i = 0; i < 24; i++) {
            axisValue[i] = i +"时";
            entries.add(new Entry(i, 10));
        }
        initLineChart(axisValue,entries);
    }

    private void initLineChart(String[] axisValue, List<Entry> entries) {
        //无数据时显示
        lineChart.setNoDataText("没有获取到数据哦~");
        lineChart.setNoDataTextColor(Color.parseColor("#00bcef"));
        //取消缩放
        lineChart.setScaleEnabled(false);

        //不显示高亮
        lineChart.setHighlightPerTapEnabled(true);

        //不显示description
        lineChart.getDescription().setEnabled(false);
        //不显示边界
        //lineChart.setDrawBorders(false);
        //不显示图例
        lineChart.getLegend().setEnabled(false);
        //lineChart.setHighlightPerDragEnabled(false);
        lineChart.setExtraBottomOffset(10f);
        //获取X轴
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(axisValue));
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(8f);
        xAxis.setTextColor(Color.parseColor("#5D6A82"));
        YAxis leftYAxis = lineChart.getAxisLeft();
        leftYAxis.setAxisMinimum(0);
        //leftYAxis.setEnabled(false);
        leftYAxis.setTextSize(8f);
        leftYAxis.setTextColor(Color.parseColor("#5D6A82"));
        YAxis rightYAxis = lineChart.getAxisRight();
        rightYAxis.setTextColor(Color.WHITE);
        rightYAxis.setEnabled(false);

        //将数据赋给数据集,一个数据集表示一条线
        LineDataSet lineDataSet = new LineDataSet(entries, "");
        //线颜色
        lineDataSet.setColor(Color.parseColor("#2AF499"));
        //线宽度
        lineDataSet.setLineWidth(1.0f);
        //显示圆点
        lineDataSet.setDrawCircles(true);
        //设置圆点颜色(外圈)
        lineDataSet.setCircleColor(Color.parseColor("#ffffff"));
        //设置圆点填充颜色
        lineDataSet.setCircleHoleColor(Color.parseColor("#008CFF"));
        //设置线条为平滑曲线
        lineDataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        //设置直线图填充
        lineDataSet.setDrawFilled(true);
        //设置填充颜色
        lineDataSet.setFillColor(Color.parseColor("#0E95C2"));
        LineData lineData = new LineData(lineDataSet);
        //不显示曲线点的具体数值
        lineData.setDrawValues(true);

        lineDataSet.setHighlightLineWidth(0.1f);
        lineDataSet.setHighLightColor(Color.parseColor("#00000000"));
        lineChart.setData(lineData);
        //刷新数据
        lineChart.invalidate();

        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
        // Set the marker to the chart
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        listenStatus = false;
        try {
            if (receiveSocket != null){
                receiveSocket.close();
            }
            if (udpReceiveThread != null) {
                udpReceiveThread.interrupt();
                udpReceiveThread.join(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,e.getMessage());
        }
        udpReceiveThread = null;
    }

    private final static int RECEIVE_PORT = 53212;

    private boolean listenStatus = false;

    private String receiveInfo;

    private DatagramSocket receiveSocket;

    public class UdpReceiveThread extends Thread {

        private final String TAG = "UdpReceiveThread";

        public UdpReceiveThread(){
        }

        @Override
        public void run() {
            Log.d(TAG, "receiving... ");
            try {
                receiveSocket = new DatagramSocket(null);
                receiveSocket.setReuseAddress(true);
                receiveSocket.bind(new InetSocketAddress(RECEIVE_PORT));
                while (listenStatus){
                    byte data[] = new byte[1024*8];
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    receiveSocket.receive(packet); // 阻塞式，接收发送方的packet
                    //取出数据长度
                    int len = packet.getLength();

                    byte[] packetByte = packet.getData();
                    byte[] messageByte = new byte[len];
                    System.arraycopy(packetByte, 0, messageByte, 0, len);
                    String ip = packet.getAddress().getHostAddress();

                    receiveInfo = AesEncryptUtils.decryptByte(messageByte);
                    JSONObject jsonObject = JSONObject.parseObject(receiveInfo);
                    jsonObject.put("sendIP",ip);
                    //Log.d(TAG, "received:  " + jsonObject);

                    Message msg = Message.obtain();
                    msg.obj = jsonObject;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "run: " + e.getMessage());
            }

        }
    }

    private List<JinChuStatusBean> inoutList = new ArrayList<>();

    public class MessageHandler extends Handler {

        String deviceIp = "";

        private final WeakReference<MainActivity> mActivity;

        public MessageHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();

            if (activity == null || msg == null || msg.obj == null) {
                return;
            }

            JSONObject obj = (JSONObject) msg.obj;
            this.handleMessage(obj);
        }

        private void handleMessage(JSONObject jsonObject) {
            //JSONObject jsonObject = JSONObject.parseObject(message);
            //Log.d(TAG, " massage: " + jsonObject);
            if (jsonObject != null){
                String type = jsonObject.getString("Type");
                deviceIp = jsonObject.getString("sendIP");
                tv_ip.setText("IP：" + deviceIp);
                JSONObject data = jsonObject.getJSONObject("Data");
                //String devID = jsonObject.getString("DevID");
                switch (type){
                    case "IAmAlive":
                        hanleHeartbeat(data);
                        break;
                    case "ReportRecord":
                        hanleRecord(data,jsonObject.getString("Site"));
                        break;
                    case "StatChange":
                        hanleStatChange(data);
                        break;
                }
            }else{
                Log.d(TAG, "空消息");
            }

        }

        private void hanleStatChange(JSONObject data) {
            Integer countTotal = 0;
            Integer attendCountTotal = 0;
            Integer presentCountTotal = 0;
            Integer workCount = 0;
            Integer managerCount = 0;
            Integer attendWorkCount = 0;
            Integer attendManagerCount = 0;
            Integer presentWorkCount = 0;
            Integer presentManagerCount = 0;
            BigDecimal xm_rate = BigDecimal.ZERO;
            BigDecimal lw_rate = BigDecimal.ZERO;
            BigDecimal gl_rate = BigDecimal.ZERO;

            try{
                String ProjName = data.getString("ProjName");
                title.setText(ProjName);

                //登记人员
                JSONObject personByClassify = data.getJSONObject("PersonByClassify");
                //出勤人员
                JSONObject attendPersonByClassify = data.getJSONObject("VisitPersonByClassify");
                //在场实时人员
                JSONObject presentPersonByClassify = data.getJSONObject("PersentPersonByClassify");

                Set<String> pbcKeySet = personByClassify.keySet();
                Set<String> apbcKeySet = attendPersonByClassify.keySet();
                Set<String> ppbcKeySet = presentPersonByClassify.keySet();

                Set<String> bcSet = new HashSet<>();
                bcSet.addAll(pbcKeySet);
                bcSet.addAll(apbcKeySet);
                bcSet.addAll(ppbcKeySet);

                for (String key : bcSet) {
                    JSONObject pbcValueJson = personByClassify.getJSONObject(key);
                    if (pbcValueJson != null) {
                        if ("普通工人".equals(pbcValueJson.getString("Name"))){
                            workCount += pbcValueJson.getInteger("Num");
                        }else if ("管理人员".equals(pbcValueJson.getString("Name"))){
                            managerCount += pbcValueJson.getInteger("Num");
                        }else if ("关键岗位".equals(pbcValueJson.getString("Name"))){
                            managerCount += pbcValueJson.getInteger("Num");
                        }
                    }

                    JSONObject apbcValueJson = attendPersonByClassify.getJSONObject(key);
                    if (apbcValueJson != null) {
                        if ("普通工人".equals(apbcValueJson.getString("Name"))){
                            attendWorkCount = apbcValueJson.getInteger("Num");
                        }else if ("管理人员".equals(apbcValueJson.getString("Name"))){
                            attendManagerCount += apbcValueJson.getInteger("Num");
                        }else if ("关键岗位".equals(apbcValueJson.getString("Name"))){
                            attendManagerCount += apbcValueJson.getInteger("Num");
                        }
                    }

                    JSONObject ppbcValueJson = presentPersonByClassify.getJSONObject(key);
                    if (ppbcValueJson != null) {
                        if ("普通工人".equals(ppbcValueJson.getString("Name"))){
                            presentWorkCount = ppbcValueJson.getInteger("Num");
                        }else if ("管理人员".equals(ppbcValueJson.getString("Name"))){
                            presentManagerCount += ppbcValueJson.getInteger("Num");
                        }else if ("关键岗位".equals(ppbcValueJson.getString("Name"))){
                            presentManagerCount += ppbcValueJson.getInteger("Num");
                        }
                    }

                }

                countTotal = workCount + managerCount;
                attendCountTotal = attendWorkCount + attendManagerCount;
                presentCountTotal = presentWorkCount + presentManagerCount;

                tv_xiangmu_renshu.setText(countTotal+"");
                tv_xiangmu_chuqing.setText(attendCountTotal+"");
                tv_xiangmu_xianchang.setText(presentCountTotal+"");
                if (countTotal > 0){
                    xm_rate = new BigDecimal(attendCountTotal).divide(new BigDecimal(countTotal),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                tv_xiangmu_lv.setText(xm_rate.toPlainString() + "%");

                tv_laowu_renshu.setText(workCount +"");
                tv_laowu_chuqing.setText(attendWorkCount +"");
                tv_laowu_xianchang.setText(presentWorkCount +"");
                if (workCount > 0){
                    lw_rate = new BigDecimal(attendWorkCount).divide(new BigDecimal(workCount),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                tv_laowu_lv.setText(lw_rate + "%");

                tv_guanli_renshu.setText(managerCount +"");
                tv_guanli_chuqing.setText(attendManagerCount +"");
                tv_guanli_xianchang.setText(presentManagerCount +"");
                if (managerCount > 0){
                    gl_rate = new BigDecimal(attendManagerCount).divide(new BigDecimal(managerCount),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
                }
                tv_guanli_lv.setText(gl_rate + "%");

            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "劳务人员管理人员分类展示出错" + e.getMessage());
            }

            try{
                int[] presentPersonNumEveryHour = data.getObject("PresentPersonNumEveryHour",int[].class);
                if (presentPersonNumEveryHour != null){
                    entries.clear();
                }
                for (int i = 0; i < presentPersonNumEveryHour.length; i++) {
                    entries.add(new Entry(i, presentPersonNumEveryHour[i]));
                }
                initLineChart(axisValue,entries);
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "现场实时人员趋势展示出错" + e.getMessage());
            }

            try{
                List<BanzuBean> workTypeList = new ArrayList<>();
                JSONObject personByWorkType = data.getJSONObject("PersonByWorkType");
                JSONObject attendPersonByWorkType = data.getJSONObject("VisitPersonByWorkType");
                JSONObject presentPersonByWorkType = data.getJSONObject("PresentPersonByWorkType");

                Set<String> pbwKeySet = personByWorkType.keySet();
                Set<String> apbwKeySet = attendPersonByWorkType.keySet();
                Set<String> ppbwKeySet = presentPersonByWorkType.keySet();

                Set<String> wtSet = new HashSet<>();
                wtSet.addAll(pbwKeySet);
                wtSet.addAll(apbwKeySet);
                wtSet.addAll(ppbwKeySet);

                BanzuBean banzuBean;
                for (String key : wtSet) {
                    String name = "";
                    Integer count = 0;
                    Integer attendCount = 0;
                    Integer presentCount = 0;
                    JSONObject personByWorkTypeJson = personByWorkType.getJSONObject(key);
                    if (personByWorkTypeJson != null) {
                        name = personByWorkTypeJson.getString("Name")==null?"":personByWorkTypeJson.getString("Name");
                        count = personByWorkTypeJson.getInteger("Num")==null?0:personByWorkTypeJson.getInteger("Num");
                    }

                    JSONObject attendPersonByWorkTypeJson = attendPersonByWorkType.getJSONObject(key);
                    if (attendPersonByWorkTypeJson != null){
                        attendCount = attendPersonByWorkTypeJson.getInteger("Num")==null?0:attendPersonByWorkTypeJson.getInteger("Num");
                        if ("".equals(name)){
                            name = attendPersonByWorkTypeJson.getString("Name")==null?"":attendPersonByWorkTypeJson.getString("Name");
                        }
                    }

                    JSONObject presentPersonByWorkTypeJson = presentPersonByWorkType.getJSONObject(key);
                    if (presentPersonByWorkTypeJson != null) {
                        presentCount = presentPersonByWorkTypeJson.getInteger("Num")==null?0:presentPersonByWorkTypeJson.getInteger("Num");
                        if ("".equals(name)){
                            name = presentPersonByWorkTypeJson.getString("Name")==null?"":presentPersonByWorkTypeJson.getString("Name");
                        }
                    }

                    banzuBean = new BanzuBean(name, count, attendCount, presentCount);
                    workTypeList.add(banzuBean);
                }

                BanzuAdapter adapter1 = new BanzuAdapter(MainActivity.this, R.layout.banzu_item, workTypeList);
                lv_gongzhong.setAdapter(adapter1);
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "工种人员展示出错" + e.getMessage());
            }

            try{
                List<BanzuBean> teamList = new ArrayList<>();
                JSONObject personByTeam = data.getJSONObject("PersonByTeam");
                JSONObject attendPersonByTeam = data.getJSONObject("VisitPersonByTeam");
                JSONObject presentPersonByTeam = data.getJSONObject("PresentPersonByTeam");

                Set<String> pbtKeySet  = personByTeam.keySet();
                Set<String> apbtKeySet = attendPersonByTeam.keySet();
                Set<String> ppbtKeySet = presentPersonByTeam.keySet();

                Set<String> tSet = new HashSet<>();
                tSet.addAll(pbtKeySet);
                tSet.addAll(apbtKeySet);
                tSet.addAll(ppbtKeySet);

                BanzuBean banzuBean;
                for (String key : tSet) {
                    String name = "";
                    Integer count = 0;
                    Integer attendCount = 0;
                    Integer presentCount = 0;
                    JSONObject personByTeamJson = personByTeam.getJSONObject(key);
                    if (personByTeamJson != null) {
                        name = personByTeamJson.getString("Name")==null?"":personByTeamJson.getString("Name");
                        count = personByTeamJson.getInteger("Num")==null?0:personByTeamJson.getInteger("Num");
                    }

                    JSONObject attendPersonByTeamJson = attendPersonByTeam.getJSONObject(key);
                    if (attendPersonByTeamJson != null){
                        attendCount = attendPersonByTeamJson.getInteger("Num")==null?0:attendPersonByTeamJson.getInteger("Num");
                        if ("".equals(name)){
                            name = attendPersonByTeamJson.getString("Name")==null?"":attendPersonByTeamJson.getString("Name");
                        }
                    }

                    JSONObject presentPersonByTeamJson = presentPersonByTeam.getJSONObject(key);
                    if (presentPersonByTeamJson != null) {
                        presentCount = presentPersonByTeamJson.getInteger("Num")==null?0:presentPersonByTeamJson.getInteger("Num");
                        if ("".equals(name)){
                            name = presentPersonByTeamJson.getString("Name")==null?"":presentPersonByTeamJson.getString("Name");
                        }
                    }

                    banzuBean = new BanzuBean(name, count, attendCount, presentCount);
                    teamList.add(banzuBean);
                }

                BanzuAdapter adapter2 = new BanzuAdapter(MainActivity.this, R.layout.banzu_item, teamList);
                lv_banzu_kaoqin.setAdapter(adapter2);
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "班组人员展示出错" + e.getMessage());
            }

            try{
                List<BanzuBean> companyList = new ArrayList<>();
                JSONObject personByCompany = data.getJSONObject("PersonByCompany");
                JSONObject attendPersonByCompany = data.getJSONObject("VisitPersonByCompany");
                JSONObject presentPersonByCompany = data.getJSONObject("PresentPersonByCompany");

                Set<String> pbcKeySet  = personByCompany.keySet();
                Set<String> apbcKeySet = attendPersonByCompany.keySet();
                Set<String> ppbcKeySet = presentPersonByCompany.keySet();

                Set<String> cSet = new HashSet<>();
                cSet.addAll(pbcKeySet);
                cSet.addAll(apbcKeySet);
                cSet.addAll(ppbcKeySet);

                BanzuBean banzuBean;
                for (String key : cSet) {
                    String name = "";
                    Integer count = 0;
                    Integer attendCount = 0;
                    Integer presentCount = 0;
                    JSONObject personByCompanyson = personByCompany.getJSONObject(key);
                    if (personByCompanyson != null) {
                        name = personByCompanyson.getString("Name")==null?"":personByCompanyson.getString("Name");
                        count = personByCompanyson.getInteger("Num")==null?0:personByCompanyson.getInteger("Num");
                    }

                    JSONObject attendPersonByCompanyJson = attendPersonByCompany.getJSONObject(key);
                    if (attendPersonByCompanyJson != null){
                        attendCount = attendPersonByCompanyJson.getInteger("Num")==null?0:attendPersonByCompanyJson.getInteger("Num");
                        if ("".equals(name)){
                            name = attendPersonByCompanyJson.getString("Name")==null?"":attendPersonByCompanyJson.getString("Name");
                        }
                    }

                    JSONObject presentPersonByCompanyJson = presentPersonByCompany.getJSONObject(key);
                    if (presentPersonByCompanyJson != null) {
                        presentCount = presentPersonByCompanyJson.getInteger("Num")==null?0:presentPersonByCompanyJson.getInteger("Num");
                        if ("".equals(name)){
                            name = presentPersonByCompanyJson.getString("Name")==null?"":presentPersonByCompanyJson.getString("Name");
                        }
                    }

                    banzuBean = new BanzuBean(name, count, attendCount, presentCount);
                    companyList.add(banzuBean);
                }

                BanzuAdapter adapter3 = new BanzuAdapter(MainActivity.this, R.layout.banzu_item2, companyList);
                lv_danwei_kaoqin.setAdapter(adapter3);
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "公司人员展示出错" + e.getMessage());
            }

        }

        //设备刷脸实时考勤
        private void hanleRecord(JSONObject data,String Site) {
            try {
                //String CustomID = data.getString("CustomID");
                //String CardID = data.getString("CardID");
                Site = Site==null?"":Site;
                String FaceImgPath = data.getString("FaceImgPath");
                String UserName = data.getString("UserName");
                Long timeStamp = data.getLong("TimeStamp");
                boolean dir = data.getBoolean("Dir");
                String Company = data.getString("CompanyName");
                String WorkType = data.getString("WorkTypeName");
                String TeamName = data.getString("TeamName");
                String Temperature = data.getString("Temperature");
                String faceImgPath = "http://" + deviceIp + FaceImgPath.replace("/database", "");

                ImageUtil.getInstance().displayImage(mContext, faceImgPath, renyuan_image, R.drawable.blank);
                tv_renyuan_name.setText(UserName);
                tv_renyuan_company.setText(Company);
                tv_renyuan_company.setSelected(true);
                tv_banzu_name.setText(TeamName);
                tv_gongzhong_name.setText(WorkType);
                tv_fangxiang.setText(dir?"进场":"出场");
                tv_shebei.setText(Site);
                tv_shijian.setText(DateUtil.formatDate(timeStamp == null ? 0L:timeStamp));
                String time = DateUtil.formatTime(timeStamp == null ? 0L:timeStamp);
                JinChuStatusBean bean = new JinChuStatusBean(UserName, TeamName, WorkType, time, Company, Temperature, Site, faceImgPath);

                if (inoutList.size() == 10 ){
                    inoutList.remove(0);
                    inoutList.add(bean);
                }else {
                    inoutList.add(bean);
                }

                intJingChuStatus();

            } catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "人员进出详细信息展示出错" + e.getMessage());
            }

        }

        private void hanleHeartbeat(JSONObject data) {
            //Log.d(TAG, "alive: "+ data.toJSONString());
            deviceIp = data.getString("IP");
            tv_ip.setText("IP：" + deviceIp);
        }

    }


}